<?php
/**
 * 检查是否为本地人
 * User: csyr
 * Date: 16/6/28
 * Time: 下午10:23
 */

namespace Home\Common\Hook;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Log;

class LocalPerson extends BaseHook
{

    public function execute($data, $params = [])
    {
        //如果已经判断为本地人则直接返回
        if ($data['is_local']) {
            return $data;
        }

        $address = $data['birthplace'];
        $country = $this->getCountryName($address);
        $data['is_local'] = false;
        $customerId = $data['id'];
        /**/
        //解决手动输入身份证的问题(发证单位空)
        $Result =D("Customer")->query("SELECT `id`,`birthplace`  FROM  `customer` WHERE  `id` ='$customerId' and `sign_organ`='' and `birthplace`<>''");
        if($Result) {
                if($Result[0]['id']>0) {
                    //$country = '迁安市';  //河北省唐山市迁安市
                    $address = $Result[0]['birthplace'];
                    if (strpos($address, '巿') !== false) {
                        $address = str_replace('巿', '市',$address);
                    }
                    if (strpos($address, '市') !== false) {
                        $country = str_replace('市', '', strstr($address, '市')).'市';
                    }
                    //例外代码
                    if($address=='河北省迁安县') {
                        $country = '迁安市';
                    }
                    if($address=='河北省定州市' || $address=='河北省定县') {
                        $country = '定州市';
                    }
                    if (strpos($country, '县市') !== false) {
                        $country = str_replace('县市', '',$country).'县';
                    }
                    if (strpos($country, '区市') !== false) {
                        $country = str_replace('区市', '',$country).'区';
                    }
                }
        }
        
        //face++ 漆滦识别问题
        $Result =D("Customer")->query("SELECT `id`  FROM  `customer` WHERE  `birthplace` like '%漆县%' and  `id` ='$customerId' and `sign_organ`<>''");
        if($Result) {
                if($Result[0]['id']>0) {
                    $country = '滦县';
                }
        }
        $Result =D("Customer")->query("SELECT `id`  FROM  `customer` WHERE  `birthplace` like '%漆南县%' and  `id` ='$customerId' and `sign_organ`<>''");
        if($Result) {
                if($Result[0]['id']>0) {
                    $country = '滦南县';
                }
        }

        if ($country) {
            $locationModel = D("CustomerLocationHistory");
            $location = $locationModel->where(['customer_id' => $customerId])->order("id desc")->find();
            similar_text($location['country'], $country, $percent);

            //本地人限制放开，属于同一个地级市的都算本地人
            $allowCityList = C("ALLOW_CITY_LIST");
            if($allowCityList[$location['city']]) {
                if(in_array($country,$allowCityList[$location['city']])) {
                    $percent = 100;
                }
            }
            if ($percent > $params['percent']) {
                $data['is_local'] = true;
            }
        } else {
            $isCountryCity = $this->isCountryCity($address);
            if ($isCountryCity) {
                $data['is_local'] = true;
            } else {
                $locationModel = D("CustomerLocationHistory");
                $location = $locationModel->where(['customer_id' => $customerId])->order("id desc")->find();
                //定位所在区县在身份证地址里
                if((strpos($address, $location['country']) !== false)) {
                    $data['is_local'] = true;
                }
            }
        }
        //内蒙
        if (strpos($address, '内蒙古') !== false || strpos($address, '甘肃') !== false) {
            $data['is_local'] = true;
        }

        //保存用户是本地人
        if ($data['is_local']) {
            D("Customer")->where(['id' => $customerId])->setField('is_local', 1);
        }
        Log::write("LOCAL DATA:".json_encode($data), Log::INFO);

        if (!$data['is_local']) {
                BusinessException::throwException(Constant::INVALID_LOCAL);
        }

        return $data;
    }

    /**
     * 判断是不是X省里的县级市
     * @param $address
     * @return bool
     */
    public function  isCountryCity($address)
    {
        $province = $this->getProvinceName($address);
        $countryCityList = C("COUNTRY_CITY_LIST");
        $cityListStr = $countryCityList[$province];
        $cityList = explode(' ', $cityListStr);
        $cityList = array_filter($cityList);
        $isCountryCity = false;
        if (is_array($cityList)) {
            foreach ($cityList as $city) {
                $city = trim($city);
                if (strpos($address, $city) !== false) {
                    $isCountryCity = true;
                    break;
                }
            }
        }
        return $isCountryCity;
    }

    /**
     * 获取身份证上的县名称
     * 两种情况，一，就是**省**县，二，就是**省**市**县
     * @param $address
     * @return bool|string
     */
    private function getCountryName($address)
    {
        if (strpos($address, '县') !== false) {
            if (strpos($address, '省') !== false) {
                $province = strstr($address, '省');
                $country = strstr($address, '县');
                $countryName = str_replace([$country, '省'], '', $province) . '县';
            }

            if (strpos($countryName, '市') !== false) {
                $countryName = str_replace('市', '', strstr($countryName, '市'));
            }
            return $countryName;
        }
        return false;
    }

    /**
     * 获取地址中的省份名称
     * 注意：暂时不支持新疆，宁夏等特殊地区
     * @param $address
     * @return bool|string
     */
    public function getProvinceName($address)
    {
        static $province = '省';
        if (false !== $pos = strpos($address, $province)) {
            $provinceName = strstr($address, $province);
            $provinceName = str_replace($provinceName, '', $address) . $province;
            return $provinceName;
        }
        return false;
    }
} 